<template>
  <view class="container">
    <image :src="new_banner.img ? new_banner.img : '../../static/images/background.png'" class="background-img" mode="aspectFill"></image>
    <view class="nav-box" :style="'margin-top: '+ (navHeight / 2) + 'px'">
      <view class="time">
        <view>{{ week }}</view>
        <view>{{ formattedDate }}</view>
      </view>
      <view class="index">首页</view>
    </view>

    <!-- 最新消息 -->
    <navigator hover-class="none" open-type="switchTab" url="/pages/msg_list/msg_list" class="msg-box" v-if="new_msg.id">
      <view class="content">
        <view class="left-box">
          <image src="../../static/images/msg.png" class="icon"></image>
          <view class="zx">最新消息</view>
          <view class="zx">|</view>
        </view>
        <view class="right-box">
          <view class="msg">{{ new_msg.title }}！</view>
          <view class="create_time">{{ new_msg.create_time_desc }}</view>
          <image src="../../static/images/right.png" class="icon"></image>
        </view>
      </view>
    </navigator>

    <!-- 功能模块 -->
    <view class="main-box">
      <view class="box" @click="goFunc(1)">
        <image src="../../static/images/box1.png"></image>
        <view class="name">项目体验</view>
      </view>
      <view class="box" @click="goFunc(2)">
        <image src="../../static/images/box2.png"></image>
        <view class="name">我的报名</view>
      </view>
      <view class="box" @click="goFunc(3)">
        <image src="../../static/images/box3.png"></image>
        <view class="name">项目申请</view>
      </view>
      <view class="box" @click="goFunc(4)">
        <image src="../../static/images/box4.png"></image>
        <view class="name">项目管理</view>
      </view>
      <view class="box" @click="goFunc(5)">
        <image src="../../static/images/box5.png"></image>
        <view class="name">补贴申请</view>
      </view>
    </view>

    <!-- 帮助中心 -->
    <view class="help-box" v-if="article_list.length">
      <image src="../../static/images/book.png"></image>
      <view class="text">帮助中心</view>
      <navigator hover-class="none" url="/pages/article_list/article_list" class="more">更多<image src="/static/images/more.png"></image></navigator>
    </view>

    <!-- 文章列表 -->
    <scroll-view scroll-y class="article-box" v-if="article_list.length">
      <view class="box" v-for="(item, index) in article_list" :key="index">
        <view class="img-box">
          <text class="text">帮 助 中 心</text>
          <view class="vice-title">{{ item.vice_title }}</view>
        </view>
        <view class="right-box">
          <view class="title">{{ item.title }}</view>
          <navigator hover-class="none" :url="'/pages/article_detail/article_detail?id=' + item.id" class="btn">立即查看</navigator>
        </view>
      </view>
    </scroll-view>


    <view id="prove-mask" v-if="show_prove" @click="empty">
      <view class="prove-mask-content" @click.stop="empty">
        <view class="prove-main-content">
          <image class="prove-close" src="/static/images/prove-close.png" @click.stop="this.show_prove = false"></image>
          <navigator hover-class="none" url="/pages/company_prove/company_prove" class="prove-box">
            <view class="line">
              <image class="icon1" src="/static/images/prove_icon2.png"></image>
              <view class="text-box">
                <view class="text">我是单位，立即认证</view>
                <view class="desc-text">申请项目、体验岗位发布</view>
              </view>
              <image class="icon2" src="/static/images/right.png"></image>
            </view>
          </navigator>
          <navigator hover-class="none" url="/pages/student_prove/student_prove" class="prove-box">
            <view class="line">
              <image class="icon1" src="/static/images/prove_icon1.png"></image>
              <view class="text-box">
                <view class="text">我是学生，立即认证</view>
                <view class="desc-text">项目体验、岗位报名</view>
              </view>
              <image class="icon2" src="/static/images/right.png"></image>
            </view>
          </navigator>
        </view>
      </view>
    </view>

    <view id="mask" v-if="show_login" @click="empty">
      <view class="mask-content" @click.stop="empty">
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="username" class="input" placeholder="请输入昵称">
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <view class="button cancel" @click="this.show_login = false">取消</view>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>

  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      week: '',
      formattedDate: '',
      navHeight: '', //整体顶部导航栏的高度
      statusBarHeight: '',//状态栏高度
      new_msg: [],// 最新消息
      new_banner: [],// 最新banner
      article_list: [],// 帮助中心
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《金翼隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      username: '',
      show_prove: false,
    }
  },

  onLoad() {
    //获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
    let {statusBarHeight, system} = uni.getSystemInfoSync()
    this.statusBarHeight = statusBarHeight
    this.navHeight = statusBarHeight + (system.indexOf('iOS') > -1 ? 40 : 44)

    var data = this.formatDate();
    this.week = data[0];
    this.formattedDate = data[1];

    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;

    // banner
    this.$http.post('/index/Api/indexBanner').then(res => {
      if (res.data.result == 1) {
        this.new_banner = res.data.data[0]
      }
    })

    // 最新消息
    this.$http.post('/index/Api/msgList', {user_id, page: 1, pagesize: 1}).then(res => {
      if (res.data.result == 1) {
        this.new_msg = res.data.data.list[0]
      }
    })

    // 帮助中心
    this.$http.post('/index/Api/articleList', {page: 1, pagesize: 3}).then(res => {
      if (res.data.result == 1) {
        this.article_list = res.data.data
      }
    })
  },

  methods: {
    formatDate: () => {
      var date = new Date();
      var days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      var week = days[date.getDay()];
      var formattedDate = `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
      return [week, formattedDate]
    },

    empty: function () {
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result == 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        index = this.index,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result == 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result == 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    var url = '';
                    switch (index) {
                      case 1:
                        url = '/pages/project_list/project_list';
                        break;
                      case 2:
                        url = '/pages/my_post/my_post';
                        break;
                      case 3:
                        url = '/pages/apply_project/apply_project';
                        break;
                      case 4:
                        url = '/pages/project_manage/project_manage';
                        break;
                      case 5:
                        url = '/pages/apply_subsidy_list/apply_subsidy_list';
                        break;
                    }
                    this.funcHref(user_id, url);

                    /*this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
                     if (resProve.data.result == 1) {
                     var {student_prove_id, company_prove_id} = resProve.data.data;
                     uni.setStorageSync('student_prove_id', student_prove_id);
                     uni.setStorageSync('company_prove_id', company_prove_id);
                     }
                     })

                     if (this.login_to_url != '/pages/project_list/project_list') {
                     uni.navigateTo({
                     url: this.login_to_url,
                     success: () => {
                     this.show_login = false;
                     this.login_to_url = '';
                     }
                     })
                     } else {
                     uni.switchTab({
                     url: this.login_to_url,
                     success: () => {
                     this.show_login = false;
                     this.login_to_url = '';
                     }
                     })
                     }*/
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })


              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            })
          }
        })
      }
    },

    goFunc: function (index) {
      var user_id = uni.getStorageSync('user_id');
      var url = '';
      switch (index) {
        case 1:
          url = '/pages/project_list/project_list';
          break;
        case 2:
          url = '/pages/my_post/my_post';
          break;
        case 3:
          url = '/pages/apply_project/apply_project';
          break;
        case 4:
          url = '/pages/project_manage/project_manage';
          break;
        case 5:
          url = '/pages/apply_subsidy_list/apply_subsidy_list';
          break;
      }

      if (!user_id) {
        uni.showLoading({
          title: '自动登录中...',
          mask: true
        })

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
              uni.hideLoading();
              if (res.data.result == 1) {
                var user_id = res.data.data;
                uni.setStorageSync('user_id', user_id)

                this.funcHref(user_id, url)
              } else {
                this.show_login = true;
                this.login_to_url = url;
              }
            })
          }
        })
      } else {
        this.funcHref(user_id, url);
      }
    },

    funcHref: function (user_id, url) {
      this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
        if (resProve.data.result == 1) {
          var {student_prove_id, company_prove_id} = resProve.data.data;
          if (student_prove_id) {
            uni.setStorageSync('student_prove_id', student_prove_id);

            if (url == '/pages/project_list/project_list' || url == '/pages/my_post/my_post') {
              if (url != '/pages/project_list/project_list') {
                uni.navigateTo({
                  url: url
                })
              } else {
                uni.switchTab({
                  url: url
                })
              }
            } else {
              // 学生点击企业权限模块
              uni.showToast({
                title: '无权限',
                icon: 'none'
              })
            }
          } else {
            if (company_prove_id) {
              uni.setStorageSync('company_prove_id', company_prove_id);

              if (url == '/pages/project_list/project_list' || url == '/pages/my_post/my_post') {
                // 企业点击学生权限模块
                uni.showToast({
                  title: '无权限',
                  icon: 'none'
                })
              } else {
                uni.navigateTo({
                  url: url
                })
              }
            } else {
              // 既没学生认证又没企业认证，跳转到认证页面
              this.show_prove = true;

              /*if (url == '/pages/project_list/project_list' || url == '/pages/my_post/my_post') {
                uni.navigateTo({
                  url: '/pages/student_prove/student_prove'
                })
              } else {
                uni.navigateTo({
                  url: '/pages/company_prove/company_prove'
                })
              }*/
            }
          }
        }
      })
    },
  }
}
</script>

<style lang="scss">
.container {
  padding: 20rpx 0;
  background: #f5f5f5;

  .background-img {
    width: 750rpx;
    height: 672rpx;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
  }

  .nav-box {
    width: calc(100% - 40rpx);
    display: flex;
    align-items: center;
    position: fixed;
    font-size: 34rpx;
    margin-left: 28rpx;
    margin-bottom: 28rpx;
    z-index: 999;

    .time {
      color: #fff;
      font-size: 24rpx;
      width: 140rpx;
    }

    .index {
      color: #fff;
      font-weight: 500;
      margin-left: calc((100% - 350rpx) / 2);
    }
  }

  .msg-box {
    position: fixed;
    width: calc(100% - 80rpx);
    margin-top: 520rpx;
    margin-left: 20rpx;
    padding: 20rpx;
    background: #fff;
    border-radius: 20rpx;
    z-index: 9999;

    .content {
      display: flex;

      .left-box {
        display: flex;
        align-items: center;

        .icon {
          width: 40rpx;
          height: 34rpx;
        }

        .zx {
          margin-left: 10rpx;
        }
      }

      .right-box {
        display: flex;
        align-items: center;
        min-width: 0;
        flex: 1;
        margin-left: 10rpx;
        font-size: 24rpx;
        color: #aaa;

        .msg {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 10rpx;
        }

        .icon {
          width: 12rpx;
          height: 24rpx;
          margin-left: 16rpx;
        }
      }
    }
  }

  .main-box {
    position: fixed;
    width: calc(100% - 60rpx);
    height: 160rpx;
    margin-top: 620rpx;
    padding: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    z-index: 9999;
    display: flex;
    justify-content: space-between;

    .box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      image {
        width: 100rpx;
        height: 100rpx;
      }

      .name {
        margin-top: 10rpx;
      }
    }
  }

  .help-box {
    position: fixed;
    width: calc(100% - 40rpx);
    margin-top: 840rpx;
    padding: 20rpx;
    z-index: 9999;
    display: flex;
    align-items: center;

    image {
      width: 36rpx;
      height: 28rpx;
    }

    .text {
      font-size: 32rpx;
      margin-left: 10rpx;
      font-weight: 500;
      flex: 1;
    }

    .more{
      color: #32A4FF;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      image{
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .article-box {
    position: fixed;
    width: calc(100% - 40rpx);
    margin-top: 920rpx;
    padding: 0 20rpx;
    z-index: 9999;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    overflow-y: auto;
    height: calc(100vh - 960rpx);

    .box {
      display: flex;
      width: 100%;
      padding: 20rpx 10rpx;
      border-radius: 12rpx;
      background: #fff;
      margin-bottom: 20rpx;

      .img-box {
        width: 260rpx;
        height: 180rpx;
        background-image: url("../../static/images/help_background.png");
        background-size: contain; /* 背景图片完全显示 */
        background-repeat: no-repeat; /* 防止背景图片重复 */
        background-position: center; /* 背景图片居中 */
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        .text {
          position: absolute;
          color: #fff;
          font-size: 20rpx;
          top: 16rpx;
          right: 24rpx;
        }

        .vice-title {
          font-size: 32rpx;
          color: #fff;
          width: 240rpx;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .img {
        width: 260rpx;
        height: 180rpx;
      }

      .right-box {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        flex-direction: column;
        flex: 1;
        padding: 24rpx 20rpx 0 20rpx;

        .title {
          width: 100%;
          font-weight: 500;
        }

        .btn {
          font-size: 24rpx;
          color: #fff;
          background: #32a4ff;
          width: 120rpx;
          padding: 10rpx 30rpx;
          border-radius: 50rpx;
          text-align: center;
        }
      }
    }
  }
}

</style>
